<template>
  <el-drawer class="edit-date-layout" v-model="drawer" :title="$t('header.editDate')">
    <div class="calendar-layout">
      <el-calendar ref="calendar" v-model="date">
        <template #header="{ date }">
          <span>{{ date }}</span>
          <el-button-group>
            <el-button @click="selectDate('prev-year')">{{ $t("header.prevYear") }}</el-button>
            <el-button @click="selectDate('prev-month')">{{ $t("header.prevMonth") }}</el-button>
            <el-button @click="selectDate('today')">{{ $t("header.today") }}</el-button>
            <el-button @click="selectDate('next-month')">{{ $t("header.nextMonth") }}</el-button>
            <el-button @click="selectDate('next-year')">{{ $t("header.nextYear") }}</el-button>
          </el-button-group>
        </template>
      </el-calendar>
    </div>
    <div class="button-layout">
      <el-button @click="closeDrawer">{{ $t("header.clearDate") }}</el-button>
      <el-button type="primary" @click="saveDateHandler">{{ $t("header.saveDate") }}</el-button>
    </div>
  </el-drawer>
</template>

<script setup lang="ts">
import { ref } from "vue";
import type { CalendarDateType, CalendarInstance } from "element-plus";
import { dayjs } from "element-plus";
import { useGlobalStore } from "@/stores";

defineOptions({
  name: "EditDateDrawer"
});

const drawer = ref(false);
const date = ref<Date>();
const calendar = ref<CalendarInstance>();
const useGlobal = useGlobalStore();

/**
 * @description 保存处理
 */
const saveDateHandler = () => {
  const dateStr = dayjs(date.value).format("YYYY-MM-DD");
  useGlobal.date = dateStr;
  drawer.value = false;
};

/**
 * @description 选择日期
 * @param {CalendarDateType} val
 */
const selectDate = (val: CalendarDateType) => {
  if (!calendar.value) return;
  calendar.value.selectDate(val);
};

/**
 * @description 打开抽屉
 */
const openDrawer = () => {
  drawer.value = true;
};

/**
 * @description 关闭抽屉
 */
const closeDrawer = () => {
  useGlobal.date = "";
  drawer.value = false;
};

defineExpose({ openDrawer, closeDrawer });
</script>

<style scoped lang="scss">
.edit-date-layout {
  .calendar-layout {
    width: 100%;
    height: calc(100% - 40px);
  }

  .button-layout {
    height: 40px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
